<template>
    <div class="common-layout">
      <el-container>
        <el-header>
            当前登录人:{{ useStore.userinfo.UserName }}
            <el-button style="float:right" type="primary" @click="Logout">退出登录</el-button>
        </el-header>
        <el-container>
          <el-aside width="200px">
            <el-menu
        active-text-color="#ffd04b"
        background-color="#545c64"
        class="el-menu-vertical-demo"
        default-active="2"
        text-color="#fff"
        @open="handleOpen"
        @close="handleClose"
      >
        <el-sub-menu index="1">
          <template #title>
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </template>
          <div v-for="(item, index) in PermissionData" :key="index" >
        <DynamicMenu :item="item" />
      </div>
      <el-menu-item index="1-1">测试页面</el-menu-item>
        </el-sub-menu>
      </el-menu>
          </el-aside>
          <el-main>
            <RouterView></RouterView>
          </el-main>
        </el-container>
      </el-container>
    </div>
  </template>

<script lang="ts" setup>
import { reactive, ref,onMounted } from 'vue'
import { ElMessage } from 'element-plus';
import { useCounterStore } from '@/stores/counter';
import {useUserStore} from '@/stores/user'
const useStore=useUserStore();
const useStorecount=useCounterStore();
import { useRouter } from 'vue-router';
const router = useRouter();
import DynamicMenu from '@/components/DynamicMenu.vue'; // 导入递归菜单组件
import { api1, api2 } from '@/main';
//@ts-ignore
import Cookies from 'js-cookie'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import type { RouteRecordRaw } from 'vue-router';

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
} from '@element-plus/icons-vue'
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}

interface Permission{
    ProfessionId:number
    ProfessionName:string
    Path:string
    Name:string
    Component:string
    Children:Permission[]
}
const PermissionData=ref<Permission[]>([]);

//退出登录
const Logout=()=>{
    router.push("/");
}

onMounted(()=>{
    loadPermission();
})

const loadPermission=()=>{
    api1.get("/api/Profession/GetTreeProfession")
    .then(async res=>{
        PermissionData.value=res.data.data;
        await addDynamicRoutes(PermissionData.value);
    })
}

//动态添加路由得函数
const addDynamicRoutes=async(PermissionData:Permission[])=>{
    await PermissionData.forEach((permission)=>{
        //创建路由对象
        const route:RouteRecordRaw={
            path:permission.Path,
            name:permission.Name,//../views/User/permission.vue
            component:()=>import('../views/User/permission.vue'),//../views/User/${permission.Component}.vue
            children:permission.Children
            ?permission.Children.map((child)=>({
                path:child.Path,
                name:child.Name,
                component:()=>import(`../views/User/${child.Component}.vue`),
            })):[],// 如果有子路由，递归生成子路由
        };
 console.log(`../views/${permission.Component}.vue`);// 获取当前的路由配置
        const routes=router.options.routes;
        // 找到父路由 MenuView
    const menuViewRoute = routes.find(route => route.name === 'MenuView');
    // 确保 menuViewRoute 存在
    if (menuViewRoute)
     {
        menuViewRoute.children?.push(route); // 使用可选链操作符，确保 children 存在
        console.log(route);
        // 重新添加路由配置
        router.addRoute(menuViewRoute);
     }
     else
     {
       console.error('父路由 MenuView 未找到，无法添加子路由');
     }
      });
      // 重新加载当前路由，确保新路由生效
      router.replace(router.currentRoute.value.path);
      const routes = router.getRoutes();
      console.log(routes);
}

</script>
